package com.wanxing.sellerapp

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.ImageView
import android.widget.MediaController
import android.widget.TextView
import android.widget.VideoView
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ShellUtils
import com.blankj.utilcode.util.ThreadUtils
import com.king.zxing.util.CodeUtils
import com.wanxing.sellerapp.audio.AudioHelper
import com.wanxing.sellerapp.config.AppConfig
import com.wanxing.sellerapp.device.KeyboardReader
import com.wanxing.sellerapp.emqx.MyMqttClient
import com.wanxing.sellerapp.platform.Api
import com.wanxing.sellerapp.seller.SellerManager
import com.wanxing.sellerapp.seller.events.AfterRegisterEvent
import com.wanxing.sellerapp.seller.events.ConfigChangeEvent
import com.wanxing.sellerapp.seller.events.ConnectChangeEvent
import com.wanxing.sellerapp.seller.events.ShowLogEvent
import com.wanxing.sellerapp.util.LimitSizeQueue
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.Queue
import java.util.Timer
import java.util.TimerTask


class MainActivity : AppCompatActivity() {

    private lateinit var tvMid: TextView
    private lateinit var tvNet: TextView
    private lateinit var tvIsClear: TextView
    private lateinit var qrcode: ImageView
    private lateinit var sellerManager: SellerManager
    private lateinit var mqttClient: MyMqttClient
    private lateinit var keyboardReader: KeyboardReader
    private lateinit var logView: View
    private lateinit var tvLog: TextView

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        event?.let { keyboardReader.feed(keyCode) }
        return true
    }

    @SuppressLint("SetTextI18n")
    private fun initView() {
        logView = findViewById(R.id.log_view)
        tvMid = findViewById(R.id.tv_mid)
        tvNet = findViewById(R.id.tv_net)
        tvIsClear = findViewById(R.id.tv_is_clear)
        qrcode = findViewById(R.id.qrcode)
        tvLog = findViewById(R.id.tvLog)
        if (!AppConfig.IZ_DEV) {
            logView.visibility = View.GONE
        }
        findViewById<TextView>(R.id.versionCode).text = "versionCode: ${AppUtils.getAppVersionCode()}"
        findViewById<TextView>(R.id.tv_uid).text = "Uid: ${DeviceUtils.getAndroidID()}"
        tvNet.text = "状态: 离线"
        tvIsClear.text = AppConfig.getAppConfig().toString()
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        AudioHelper.init(this)
        sellerManager = SellerManager()
        mqttClient = MyMqttClient(this, sellerManager)
        mqttClient.init()
        keyboardReader =  KeyboardReader{
            val seller = sellerManager.seller
            showLog(ShowLogEvent("扫描到卡$it", "", ))
            if (null == seller) {
                showLog(ShowLogEvent("网络错误", "", ))
                AudioHelper.play(AudioHelper.SOUND_NET_ERROR) //设备网络错误
                return@KeyboardReader
            }
            if (seller.canOpenDoor()) {
                AppExecutors.networkIO.execute {
                    val cardNo = if (AppConfig.DEFAULT_CHANNEL == "local") "0207983675" else it
                    showLog(ShowLogEvent("下单,卡号: $cardNo", ""))
                    val res = Api.balanceOrder(cardNo)
                    showLog(ShowLogEvent("下单结果: $res", res.orderId))
                    when (res.code) {
                        "0" -> seller.openDoor(1, res.orderId, res.createTime)
                        "1" -> AudioHelper.play(AudioHelper.SOUND_D_NOT_REG) //设备未注册
                        "2" -> AudioHelper.play(AudioHelper.SOUND_D_NOT_USE) //设备未启用
                        "3" -> AudioHelper.play(AudioHelper.SOUND_NO_BALANCE) //余额不足
                        "-1" -> AudioHelper.play(AudioHelper.SOUND_NET_ERROR) //设备网络错误
                        "500"->  AudioHelper.play(AudioHelper.SOUND_SYS_ERROR) //系统内部异常
                        "40002","40001"->  AudioHelper.play(AudioHelper.SOUND_CARD_INVALIDATE) //卡号不存在
                        "40003"->  AudioHelper.play(AudioHelper.SOUND_CARD_FROZEN) //卡已挂失或停用
                        "40004"->  AudioHelper.play(AudioHelper.SOUND_CARD_SX) //卡已失效
                        "40006"->  AudioHelper.play(AudioHelper.SOUND_CARD_EXPIRE) //卡已过期
                        else -> AudioHelper.play(AudioHelper.SOUND_SYS_ERROR)
                    }
                }
            }
        }
        playAdvVideo()
    }


    private var exitCount = 0
    private var clearTask:TimerTask? = null
    private fun playAdvVideo() {
        val videoView = findViewById<VideoView>(R.id.videoView)
        val mediaController = MediaController(this)
        mediaController.setMediaPlayer(videoView)
        videoView.setMediaController(mediaController)
        val url = AppConfig.getAdvUrl()
        if (!TextUtils.isEmpty(url)) {
            AppExecutors.networkIO.execute {
                val path = Api.getAdvPath(url)
                runOnUiThread {
                    videoView.setVideoPath(path)
                }
            }

        }
        Api.onAdvUrlChange = {
            AppExecutors.networkIO.execute {
                val path = Api.getAdvPath(url)
                runOnUiThread {
                    videoView.setVideoPath(path)
                }
            }
        }
        videoView.setOnPreparedListener {
            it.start()
            it.isLooping = true
        }
        // 2S之内触摸50次退出应用（一个触摸点算一次，可以用5个手指头快速摸5次以上）
        videoView.setOnTouchListener { _, _ ->
            clearTask?.cancel()
            clearTask = object : TimerTask() { override fun run() { exitCount = 0 } }
            Timer().schedule(clearTask, 2 * 1000)
            if (++exitCount == 40) {
                ShellUtils.execCmd("am force-stop com.wanxing.sellerapp", true, false)
            }
            return@setOnTouchListener true
        }
    }

    override fun onStart() {
        super.onStart()
        tvNet.text = if (SPUtils.getInstance().getBoolean("mq_conn",false)) "状态: 在线" else "状态:离线"
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAfterRegister(event: AfterRegisterEvent) {
        tvMid.text = "编号：${event.seller.mid}"
        showQrcode(event.seller.mid)
    }

    private fun showQrcode(mid: Int) {
        ThreadUtils.executeByIo(object :ThreadUtils.Task<Bitmap>(){
            override fun doInBackground() = CodeUtils.createQRCode("https://mwx.wanxingshangye.com?type=seller&mid=$mid&doorId=1",600)
            override fun onSuccess(bitmap: Bitmap?) {
                qrcode.setImageBitmap(bitmap)
            }
            override fun onCancel() {}
            override fun onFail(t: Throwable?) {}
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onConnectChange(event: ConnectChangeEvent) {
        tvNet.text = if (event.isOnline) "状态: 在线" else "状态:离线"
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onConfigChange(event: ConfigChangeEvent){
        tvIsClear.text = AppConfig.getAppConfig().toString()
    }

    override fun onDestroy() {
        mqttClient.release()
        super.onDestroy()
    }

    private val logQueue: Queue<String> = LimitSizeQueue(15)

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    fun showLog(logEvent: ShowLogEvent) {
        if (AppConfig.IZ_DEV) {
            logQueue.add(logEvent.log)
            val log = StringBuilder()
            for (s in logQueue) {
                log.append("$s\n")
            }
            runOnUiThread {
                tvLog.text = log.toString()
            }
        }

    }

}